<?php
class Leonardo extends MY_Controller {

	public function __construct() {
		parent::MY_Controller();

		$this->load->helper(array('form','url', 'language'));
		$this->load->library('form_validation');

		$this->lang->load('home');
		$this->lang->load('login');
		$this->lang->load('signup');
		$this->lang->load('profile');
		$this->lang->load('form_validation');
		$this->lang->load('leonardo');
	}

	public function one() {
		$leoUser = $this->input->post('leonardo_user');
		$leoPass = $this->input->post('leonardo_pass');

		$this->_renderOne($leoUser, $leoPass);
	}

	public function two() {
		$leoUser = $this->input->post('leonardo_user');
		$leoPass = $this->input->post('leonardo_pass');

		if (!$this->input->post('action')) {
			// can't be here without having post'ed from one!
			$this->redirect('signup/index', "Can't go to step two without doing step one!", true);
		}
		else { // process form from step 1
			if ($this->_one_validate() === TRUE) {
                $person = null;
				try {
					$person = $this->_processOne();
				}
				catch (Exception $e) {
					$this->render('signup/index', null, $this->error(array(
                        'message' => 'Ooops, the account could not be created - contact Administrator',
                        'exception' => $e
					)));

					return false;
				}
				
				$this->redirect('login', 'Account created successfully, please login.');
			}
			else {
				$this->_renderOne($leoUser, $leoPass, true);
			}
		}
	}

	private function _renderOne($leoUser, $leoPass, $errors = false) {
		if (!$leoUser || !$leoPass) {
			$this->redirect('signup/index', 'You have to specify both Leonardo username and password', true);
			return;
		}

		$phpbbUser = Doctrine::getTable('PhpbbUserModel')->findOneByUsername($leoUser);

		if ($phpbbUser == null) {
			$this->redirect('signup/index', 'Could not find Leonardo user with the given name', true);
			return;
		}

		if (md5($leoPass) != $phpbbUser->user_password) {
			$this->redirect('signup/index', 'Invalid password specified for Leonardo username', true);
			return;
		}

		$leonardoPilot = Doctrine::getTable('LeonardoPilotModel')->findOneByPilotID($phpbbUser->user_id);

		if ($leonardoPilot == null) {
			$this->redirect('signup/index', 'Could not find the Leonardo pilot user', true);
			return;
		}

		$person = new PersonModel();
		$person->id = $leonardoPilot->civl_id;
		$person->name = $leonardoPilot->firstname.' '.$leonardoPilot->lastname;
		$person->email_primary = $phpbbUser->user_email;
		$person->country_code = $leonardoPilot->countrycode;
		//$person->password = $this->input->post('leonardo_pass');

		$pilot  = new PilotModel();
		$pilot->helmet = $leonardoPilot->helmet;
		$pilot->harness = $leonardoPilot->harness;
		$pilot->gps = $leonardoPilot->gps;
		$pilot->vario = $leonardoPilot->vario;
		$pilot->rescue = $leonardoPilot->reserve;
		$pilot->sponsor = $leonardoPilot->sponsor;
		$pilot->comments = $leonardoPilot->personalwebpage;
		$pilot->leonardo_id = $leonardoPilot->pilotid;

		$person->Pilot = $pilot;

		$data['leonardo_user'] = $leoUser;
		$data['leonardo_pass'] = $leoPass;
		$data['leonardo_pilot'] = $leonardoPilot->pilotid;
		$data['person'] = $person;
		$data['pilot'] = $pilot;

		if ($errors) {
			$this->render('leonardo/one', $data, $this->error(validation_errors('<li>','</li>')));
		}
		else {
			$this->render('leonardo/one', $data);
		}
	}

	private function _processOne() {
		$p = new PersonModel();
		$p->merge($_POST);
		
		$leonardoPilot = Doctrine::getTable('LeonardoPilotModel')->findOneByPilotID($this->input->post('leonardo_pilot'));
        if ($leonardoPilot == null) {
            throw new Exception('Could not find the Leonardo pilot user');
        }
		
        $pilot = new PilotModel();
        $pilot->helmet = $leonardoPilot->helmet;
        $pilot->harness = $leonardoPilot->harness;
        $pilot->gps = $leonardoPilot->gps;
        $pilot->vario = $leonardoPilot->vario;
        $pilot->rescue = $leonardoPilot->reserve;
        $pilot->sponsor = $leonardoPilot->sponsor;
        $pilot->comments = $leonardoPilot->personalwebpage;
        $pilot->leonardo_id = $leonardoPilot->pilotid;
		
        
        if ($leonardoPilot->nacclubid) {
            $club = ClubModel::getLeonardoClub($leonardoPilot->nacclubid);
            
            if ($club !== false) {
            	$pilot->Clubs[] = $club;
            }
        }
        
        $p->Pilot = $pilot;
        $p->save();

		// find the 'User' role and add it to the new user
		$p->Roles[] = RoleModel::findByName('User');
		$p->save();

		return $p;
	}
	
	public function aaa($civlid) {
		$this->_preRender($civlid);

		$person = PersonModel::getPerson($civlid);
		$pilot = $person->Pilot;

		if (!$this->input->post('action')) {
			$this->redirect('profile/pilot/edit/'.$civlid);
			return;
		}

		$phpbbUser = Doctrine::getTable('PhpbbUserModel')->findOneByUsername($this->input->post('cnd_user'));

		if ($phpbbUser == null) {
			$this->redirect('profile/pilot/edit/'.$civlid, 'PhpBB user not found - contact Administrator', true);
			return;
		}

		if (md5($this->input->post('cnd_password')) != $phpbbUser->user_password) {
			$this->redirect('profile/pilot/edit/'.$civlid, 'Wrong CND username or password - try again', true);
			return;
		}

		$leonardoPilot = Doctrine::getTable('LeonardoPilotModel')->findOneByPilotID($phpbbUser->user_id);

		if ($leonardoPilot == null) {
			$this->redirect('profile/pilot/edit/'.$civlid, 'Leonardo/CND user not found - contact Administrator', true);
			return;
		}

		//echo 'Ok, user_id = '.$leonardoPilot->firstname.'<br/>';
		$pilot->helmet = $leonardoPilot->helmet;
		$pilot->harness = $leonardoPilot->harness;
		$pilot->gps = $leonardoPilot->gps;
		$pilot->vario = $leonardoPilot->vario;
		$pilot->rescue = $leonardoPilot->reserve;
		$pilot->sponsor = $leonardoPilot->sponsor;
		$pilot->comments = $leonardoPilot->personalwebpage;

		$data['person'] = $person;
		$data['pilot'] = $pilot;

		$this->render('profile/pilot', $data);
	}

	private function _one_validate() {
		$this->_loadValidationMessages();
		
		// validation rules
		$this->form_validation->set_rules('id', 'lang:civl_id','required|numeric|min_length[3]|max_length[12]|unique[PersonModel.id]');
		$this->form_validation->set_rules('password', 'lang:password','required|min_length[3]|max_length[12]');
		$this->form_validation->set_rules('passconf', 'lang:passconf', 'required|matches[password]');
		$this->form_validation->set_rules('name', 'lang:name', 'required|xss_clean');
		$this->form_validation->set_rules('email_primary', 'lang:email', 'required|valid_email|unique[PersonModel.email_primary]');

		return $this->form_validation->run();
	}

}
